<template>
  <div class="group_list">

    <a-card style="margin-top: 10px;">
      <div class="list_title">
        <span>用户分群列表</span>
        <a-button type="primary" class="set_up" @click="showEditModal('add')" icon="plus" v-action:add="'userProfile.userGroup'">添加</a-button>
      </div>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading.table"
        :scroll="{x: true}"
        rowKey="id"
        @change="onTableChange"
        style="margin-top:10px; margin-bottom:5px;"
      >
        <template slot="name" slot-scope="text, record">
          <div class="group_name_wrapper">
            <a class="group_name" @click="checkDetails(record.id)">{{ text }}</a>
          </div>
        </template>
        <template slot="type" slot-scope="text, record">
          <div>
            <a-tag :color=" record.type === 1 ? 'green':'cyan' ">{{ record.type === 1 ? '手动更新' : '自动更新' }}</a-tag>
          </div>
        </template>
        <template slot="status" slot-scope="text, record">
          <div>
            <span>{{ getStatusLabel(record.status) }}</span>
          </div>
        </template>
        <template slot="action" slot-scope="text, record">
          <div>
            <a-row>
              <a @click="showEditModal('edit', record)" v-action:edit="'userProfile.userGroup'">编辑</a>
              <a-divider type="vertical" style="opacity: 0;" v-action:edit="'userProfile.userGroup'"/>
              <a @click="deleteGroup(record)" v-action:delete="'userProfile.userGroup'">删除</a>
              <a-divider type="vertical" style="opacity: 0;" v-action:delete="'userProfile.userGroup'"/>
              <a v-if="record.type === 1" @click="manualUpdate(record)">手动更新</a>
              <a-divider v-if="record.type === 1" type="vertical" style="opacity: 0;"/>
              <a v-if="checkAutoExportStatus(record)"  target="_blank" :href="downloadSrc(record)" style="color: #50b14e;text-decoration: underline">下载明细</a>
            </a-row>
          </div>
        </template>
      </a-table>
    </a-card>

    <GroupingEditModal
      v-bind:datasourceList="datasourceList"
      v-bind:formModel="formModel"
      v-bind:group="group"
      v-on:loadUserGroups="getUserGroupList">

    </GroupingEditModal>

  </div>
</template>

<script>

import {deleteUserGroupApi, getUserGroupListApi, manualUpdateUserGroupDataApi} from "@/api/userGroup";
import GroupingEditModal from "@/views/userProfile/userGroup/components/GroupingEditModal";
import {getDatasourceListByOrgId} from "@/api/orgManage";
import store from "@/store";
import EventConfigUtil from "@/utils/EventConfigUtil";

const columns = [
  {
    title: '分群名称',
    dataIndex: 'name',
    width: 200,
    scopedSlots: { customRender: 'name'}
  },
  {
    title: '用户',
    dataIndex: 'users',
    width: 150,
  },
  {
    title: '更新方式',
    dataIndex: 'type',
    width: 150,
    scopedSlots: { customRender: 'type'}
  },
  {
    title: '最近更新状态',
    dataIndex: 'status',
    width: 150,
    scopedSlots: { customRender: 'status'}
  },
  {
    title: '操作',
    width: 200,
    fixed: 'right',
    scopedSlots: { customRender: 'action'}
  },
]
export default {
  name: "GroupList",
  components: {GroupingEditModal},
  data() {
    return {
      columns,
      loading: {
        table: false
      },
      tableData: [],
      pagination:{
        current : 1,
        pageSize: 10,
        total: 0,
        pageSizeOptions: ['10', '30', '50', '100'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal : (total)=>{
          return `共  ${total}  条记录   第  ${this.pagination.current} / ${Math.ceil(this.pagination.total/this.pagination.pageSize)}  页 `
        }
      },
      groupList: [],
      datasourceList: [],
      defaultFormModel: {
        visible: false,
        loading: false,
        data:{}
      },
      formModel: {},
      defaultGroupConf: {
        datasourceId: null,
        name: "",
        type: 0,
        exportConfig: {
          autoExport: 0,
          exportType: "CSV"
        },
        config: {
          condition: "AND",
          user_rule: {
            condition: "AND",
            rules: [],
          },
          event_rule: {
            condition: "AND",
            rules: [],
          },
          actions_rule:{
            condition: "AND",
            rules:[]
          }
        }
      },
      group: {}
    }
  },
  methods: {
    initPageData (){
      this.getUserGroupList()
      this.getDataSourceList()
    },
    getDataSourceList(){
      let orgId = store.getters.selectedOrg.id
      if (!orgId) {
        return
      }
      getDatasourceListByOrgId(orgId, {}).then(res => {
        if(res.status && res.data) {
          this.datasourceList = res.data.filter(datasource => datasource.type === 0)
        } else {
          this.$message.error('数据源列表获取失败，原因：' + res.msg)
        }
      }).catch(err => {
        this.$message.error('数据源列表获取失败，原因：' + err)
      })
    },
    getUserGroupList(){
      this.loading.table = true
      getUserGroupListApi().then(res=>{
        if (res && res.code === 0){
          this.groupList = res.data
          this.pagination.total = res.data.length
          this.setTableData()
        }else {
          this.$message.error('用户分群列表获取失败，原因：' + res.msg)
        }
      }).catch(err=>{
        this.$message.error('用户分群列表获取失败，原因：' + err)
      }).finally(()=>{
        this.loading.table = false
      })
    },
    setTableData (){
      if (!this.groupList || this.groupList.length < 1){
        this.tableData = []
        return
      }
      const start = (this.pagination.current - 1) * this.pagination.pageSize
      const last = start + this.pagination.pageSize
      const end = last >= this.pagination.total ? this.pagination.total : last
      this.tableData = this.groupList.slice(start, end)
    },
    onTableChange (page) {
      this.pagination.current = page.current
      this.pagination.pageSize = page.pageSize
      this.setTableData()
    },
    showEditModal(type,record){
      if (type === 'edit' && record){
        let group = JSON.parse(JSON.stringify(this.defaultGroupConf))
        group.name = record.name
        group.type = record.type
        group.id = record.id
        group.datasourceId = record.datasourceId
        if (record.exportConfig && record.exportConfig.length > 0){
          try {
            group.exportConfig = JSON.parse(record.exportConfig)
          }catch (e){
            console.error(e)
            return
          }
        }
        let conf = JSON.parse(record.config)
        if (typeof conf.actions_rule !== "object"){
          conf.actions_rule ={ condition: "AND", rules:[]}
        }
        group.config = EventConfigUtil.insertKey(conf);
        this.group = group
        const form = JSON.parse(JSON.stringify(this.defaultFormModel))
        form.type = "edit"
        form.visible = true
        this.formModel = form
      }else {
        this.group = JSON.parse(JSON.stringify(this.defaultGroupConf))
        const form = JSON.parse(JSON.stringify(this.defaultFormModel))
        form.visible = true
        form.type = "add"
        this.formModel = form
      }
    },
    deleteGroup(record) {
      this.$confirm({
        title: '删除分群',
        content: '删除分群后数据无法恢复，您确定删除此分群吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          deleteUserGroupApi(record.id).then(res => {
            if(res.status) {
              this.$message.success('用户分群删除成功')
            } else {
              this.$message.error('用户分群删除失败，原因：' + res.msg)
            }
          }).catch(err => {
            this.$message.error('用户分群删除失败，原因：' + err)
          })
        },
        onCancel: () => {},
      })

    },
    manualUpdate(record) {
      this.$confirm({
        title: '手动更新分群',
        content: '更新分群数据可能需要较长时间，执行更新后请过一会儿回来查看结果。您确定手动更新分群数据吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          manualUpdateUserGroupDataApi(record.id).then(res => {
            if(res.status) {
              this.$message.success("更新任务已提交，请稍后回来查看结果！");
            } else {
              this.$message.error("执行更新任务失败,请稍后重试！");
            }
          }).catch(err => {
            this.$message.error("执行更新任务失败,请稍后重试！");
          })
        },
        onCancel: () => {},
      })

    },
    checkDetails (id){
      this.$router.push({
        name: 'UserDetailList',
        query: {
          user_group_id: id
        }
      })
    },
    getStatusLabel(status) {
      let label = "未知";
      switch(status) {
        case 0:
          label = '运行中';
          break;
        case 1:
          label = '成功';
          break;
        case 2:
          label = '失败';
          break;
      }
      return label;
    },
    checkAutoExportStatus(record) {
      let expConfig = (typeof record.exportConfig === 'string') ? JSON.parse(record.exportConfig):null;
      if (expConfig && expConfig.autoExport === 1 && record.status === 1 && record.userGroupExportTasks && record.userGroupExportTasks.status === 2){
        if (record.userGroupExportTasks && typeof record.userGroupExportTasks.filePath === 'string' && record.userGroupExportTasks.filePath.length > 0){
          return true
        }
      }
      return false;
    },
    downloadSrc(record){
      if (record.userGroupExportTasks.filePath){
        return "http://" + window.location.host+ record.userGroupExportTasks.filePath
      }else {
        return ""
      }
    }
  },
  mounted() {
    this.initPageData()
  },
  created() {
    this.group = JSON.parse(JSON.stringify(this.defaultGroupConf))
  }
}
</script>

<style scoped>
  .group_list{
    width: 100%;
    height: 100%;
  }

  .list_title{
    display: flex;
    justify-content: space-between;
  }


  .list_title span {
    display: block;
    float: left;
    margin-bottom: 0;
    padding-right: 12px;
    color: rgba(0,0,0,.85);
    font-weight: 500;
    font-size: 16px;
    line-height: 32px;
  }

  .group_name {
    color: #50b14e;
    text-decoration: underline;
  }
</style>
